package com.xxyf.filter;

import com.xxyf.domain.JwtUtil;
import com.xxyf.eoro.RunAuth;
import com.xxyf.service.LogUserDetaImp;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.lang.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小小怡飞
 * @Date 2022/12/6 21:29
 * @Version JDK 8
 */
@Component
@Slf4j
public class LoginFilter extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!Strings.hasText(token)) {
//            进行判断对登录接口正常放行不设限制
            if (request.getRequestURI().equals("/login.do")){
                filterChain.doFilter(request, response);
                return;
            }
            UsernamePasswordAuthenticationToken token1 =
                    new UsernamePasswordAuthenticationToken(null, null, null);
            SecurityContextHolder.getContext().setAuthentication(token1);
            filterChain.doFilter(request, response);
            return;

        }
//        检查token是否合法
        String subject;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            subject = claims.getSubject();
        } catch (Exception e) {

            throw new RunAuth("token异常");
        }
//        获取并重置过期时间
        LogUserDetaImp userDetaImp = (LogUserDetaImp) redisTemplate.opsForValue().get("login:" + subject);
        redisTemplate.expire("login:" + subject,30*60, TimeUnit.SECONDS);
        if (userDetaImp==null){
            throw new RunAuth("用户无权限");
        }

        UsernamePasswordAuthenticationToken token1 =
                new UsernamePasswordAuthenticationToken(userDetaImp, null, userDetaImp.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(token1);
        filterChain.doFilter(request,response);
    }
}
